package my.example.samplegridview;
//55D52D33F3A78D61162DB444FC
import java.io.BufferedInputStream;
import java.util.Vector;

import my.example.samplegridview.modal.category;
import my.example.samplegridview.modal.product;
import my.example.samplegridview.modal.product_to_category;
import my.example.samplegridview.modal.user;
import o2s.utils.imageHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class samplegridview extends Activity {
    /** Called when the activity is first created. */
	
	Context _context;
	AssetManager _assetManager;
	samplegridview _self;
	public static int requestcode = 500;
	public String currentCatName = "";
	public static Vector<samplegridview> stackView;
	public static boolean hasProduct;
	public TextView breadCrum;
	public int id;
	public OrderPreviewAdapter opa;
	private headerbarmain hbm;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        _self = this;
        _context = this.getBaseContext();
        _assetManager = getAssets();
        Intent i = getIntent();
        
        hbm = (headerbarmain)findViewById(R.id.testingheaderbar);
        hbm.setAct(this);
        
        String categoryid = i.getStringExtra("categoryid");
        LinearLayout productviewlayer = (LinearLayout) findViewById(R.id.productviewlayer);
        LinearLayout maincategoryviewlayer = (LinearLayout) findViewById(R.id.maincategoryviewlayer);
        GridView maincatgridview = (GridView) findViewById(R.id.maincategoryview);
        GridView gridview = (GridView) findViewById(R.id.productview);
        Gallery g = (Gallery) findViewById(R.id.categoryview);
        
        if(categoryid.compareTo("0") == 0){
        	
        	this.addBreadCrum("Main",0,true);
        	
        	//Load maincategory
        	g.setVisibility(View.GONE);
        	productviewlayer.setVisibility(View.GONE);
        	
        	maincategoryviewlayer.setVisibility(View.VISIBLE);
        	Vector<category> subCategory = subcatInitialization(categoryid);
        	
        	maincatgridview.setAdapter(new MainCategoryAdapter(this, subCategory));
        	
        	View seperator = findViewById(R.id.mainseperator);
        	seperator.setVisibility(View.GONE);
        }
        else{
        	category ctmp = new category(_context, categoryid);
        	currentCatName = ctmp.getCatdescription().getName();
        	
        	Log.d("stackView.size()", String.valueOf(stackView.size()));
        	for(int k=0;k<stackView.size();k++){
        		this.addBreadCrum(stackView.get(k).breadCrum.getText().toString() + "->" , k , false);
        	}
        	this.addBreadCrum(currentCatName,stackView.size() , true);
        	
        	//Load subcategory
            Vector<category> subCategory = subcatInitialization(categoryid);
            Vector<product> products = productInitialization(categoryid);
            
            gridview.setAdapter(new ProductAdapter(this,products,samplegridview.this));
            
            View seperator = findViewById(R.id.mainseperator);
            if(products.size() == 0){
            	productviewlayer.setVisibility(View.GONE);
            	seperator.setVisibility(View.GONE);
            	hasProduct = false;
            }
            else{
            	hasProduct = true;
            }
            
            if(subCategory.size() == 0){
            	seperator.setVisibility(View.GONE);
            	g.setVisibility(View.GONE);
            }
            g.setAdapter(new CategoryAdapter(this,subCategory));
        }
		
		if(stackView == null)
        	stackView = new Vector<samplegridview>();
        	
        stackView.add(this);
    }
    
    @Override
	protected void onDestroy(){
    	stackView.remove(stackView.lastElement());
    	super.onDestroy();
    }
    
    public Vector<category> subcatInitialization(String subcategoryid){
    	Vector<category> categories = new Vector<category>();
    	
    	String[] args = {subcategoryid};
    	Cursor c = getContentResolver().query(category.CONTENT_URI, null, "parent_id=?",args, null);
    	while(c.moveToNext()){
    		category cat = new category(this,String.valueOf(c.getInt(0)));
    		cat.setCategory_id(String.valueOf(c.getInt(0)));
    		cat.setImage(c.getString(1));
    		cat.setParent_id(String.valueOf(c.getInt(2)));
    		cat.setSort_order(String.valueOf(c.getInt(3)));
    		cat.setDate_added(c.getString(4));
    		cat.setDate_modified(c.getString(5));
    		cat.setStatus(String.valueOf(c.getInt(6)));
    		categories.add(cat);
    	}
    	c.close();
    	
        return categories;
    }
    
    public Vector<product> productInitialization(String subcategoryid){
    	Vector<product> products = new Vector<product>();
    	
    	String[] args = {subcategoryid};
    	Vector<String> productids = new Vector<String>();
    	Cursor c = getContentResolver().query(product_to_category.CONTENT_URI, null, "category_id=?",args, null);
    	while(c.moveToNext()){
    		productids.add(c.getString(0));
    	}
    	c.close();
    	
    	for(int i=0;i<productids.size();i++){
    		product p = new product(_context,productids.get(i));
    		products.add(p);
    	}
    	
    	return products;
    }
    
    public class MainCategoryAdapter extends BaseAdapter {
    	 private Context mContext;
         private Vector<category> maincategory;

         public MainCategoryAdapter(Context c , Vector<category> maincategory) {
             mContext = c;
             this.maincategory = maincategory;
         }
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.maincategory.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return this.maincategory.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final category c = maincategory.get(arg0);
        	
        	LinearLayout categoryView = null;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
            	LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            	categoryView = (LinearLayout) li.inflate(R.layout.category, null);
            } else {
            	categoryView = (LinearLayout) convertView;
            }
            
            BufferedInputStream buf = null;
			//Set Image
			ImageView iv = (ImageView)categoryView.findViewById(R.id.categoryimage);
			
			if(c.getImage().length() > 0){
				int indexer = c.getImage().lastIndexOf("/");
				String imageName = c.getImage().substring(indexer+1);
				Bitmap bitmap = imageHelper.readImageFromUrl(imageName, _context);
				//Bitmap bitmap = imageHelper.getImageFromResource(_context,p.getImage());
				iv.setImageBitmap(bitmap);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
			}	
			
			//Set Category Name
			TextView tv = (TextView)categoryView.findViewById(R.id.categoryname);
			if(c.getCatdescription().getName() != null && c.getCatdescription().getName().length() > 0)
				tv.setText(c.getCatdescription().getName());
			else
				tv.setVisibility(View.GONE);
			//TextView tv = (TextView)categoryView.findViewById(R.id.categoryname);
			//tv.setVisibility(View.GONE);
			
			//categoryView.setBackgroundResource(mGalleryItemBackground);
			
			//set category selected event
			categoryView.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent i = new Intent(_self,samplegridview.class);
					i.putExtra("categoryid", c.getCategory_id());
					_self.startActivityForResult(i, samplegridview.requestcode);
				}
				
			});
			
			return categoryView;
		}
    	
    }
    
    public class CategoryAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
        private Vector<category> categories;

        public CategoryAdapter(Context c , Vector<category> categories) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.HelloGallery_android_galleryItemBackground, 0);
            a.recycle();
            
            this.categories = categories;
        }

        @Override
		public int getCount() {
            return this.categories.size();
        }

        @Override
		public Object getItem(int position) {
            return position;
        }

        @Override
		public long getItemId(int position) {
            return position;
        }

        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
        	
        	final category c = categories.get(position);
        	
        	LinearLayout categoryView = null;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
            	LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            	categoryView = (LinearLayout) li.inflate(R.layout.category, null);
            } else {
            	categoryView = (LinearLayout) convertView;
            }
            
            BufferedInputStream buf = null;
            
            //Set Image
            ImageView iv = (ImageView)categoryView.findViewById(R.id.categoryimage);
            if(c.getImage().length() > 0){
				int indexer = c.getImage().lastIndexOf("/");
				String imageName = c.getImage().substring(indexer+1);
				Bitmap bitmap = imageHelper.readImageFromUrl(imageName, _context);
				//Bitmap bitmap = imageHelper.getImageFromResource(_context,p.getImage());
				if(hasProduct){
					iv.setLayoutParams(new LinearLayout.LayoutParams(120,120));
				}
				else{
					iv.setLayoutParams(new LinearLayout.LayoutParams(180,180));
				}
				iv.setImageBitmap(bitmap);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
			}
            
			//Set Category Name
			TextView tv = (TextView)categoryView.findViewById(R.id.categoryname);
			if(c.getCatdescription().getName() != null && c.getCatdescription().getName().length() > 0)
				tv.setText(c.getCatdescription().getName());
			else
				tv.setVisibility(View.GONE);
			
			//categoryView.setBackgroundResource(mGalleryItemBackground);
			
			//set category selected event
			categoryView.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent i = new Intent(_self,samplegridview.class);
					i.putExtra("categoryid", c.getCategory_id());
					_self.startActivityForResult(i, samplegridview.requestcode);
				}
				
			});
			
			return categoryView;
        }
    }    
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(resultCode == productdescription.activitycode){
        	hbm.reloadBatch();
        }
    }
    
    @Override
	protected void onResume(){
    	hbm.reloadBatch();
    	super.onResume();
    }

    private void addBreadCrum(String txt , int id , boolean isFocus){
    	
    	this.breadCrum = new TextView(this);
    	if(isFocus){
    		SpannableString ss = new SpannableString(txt);
        	ss.setSpan(new ForegroundColorSpan(Color.YELLOW), 0,ss.length(), 0);
        	this.breadCrum.setText(ss);
    	}
    	else{
    		this.breadCrum.setTextColor(Color.WHITE);
    		this.breadCrum.setText(txt);
    	}
    	this.breadCrum.setTag(id);
    	
    	this.breadCrum.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				for(int i=stackView.size()-1;i>0;i--){
					if(i==0){
						Log.d("size1",String.valueOf(stackView.size()));
						break;
					}
					
					if(Integer.parseInt(arg0.getTag().toString()) < i){
						samplegridview tmp = stackView.get(i);
						tmp.finish();
					}
					else{
						//samplegridview tmp = stackView.get(i);
						Log.d("size2",String.valueOf(stackView.size()));
						break;
					}
				}
			}
    		
    	});
    	this.breadCrum.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22);
    	LinearLayout ll = (LinearLayout)findViewById(R.id.mainbreadcrumlayer);
    	ll.addView(this.breadCrum);
    }
    
    private void removeBreadCrum(){
    	LinearLayout ll = (LinearLayout)findViewById(R.id.mainbreadcrumlayer);
    	ll.removeView(this.breadCrum);
    }
}